package thomas.movie;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class EnglishSubtitles {

    public static final String strStart = "{\\4c&H000000&}";
    public static final String fileNameSuffix = ".ass";
    public static final String outputFNSuffix = ".txt";
    //source file encoding is: UCS-2 LE BOM
    public static final Charset UTF16LE = Charset.forName("UTF-16LE");
    public static final Charset UTF8 = Charset.forName("UTF-8");
    public void subtitlesForFile(File file){
        //File file = new File(sourceFileName);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF16LE));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(new File(file.getParent(), file.getName() + outputFNSuffix)), UTF8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                //System.out.println(line);
                if (line.contains(strStart)) {
                    writer.write(line.substring(line.indexOf(strStart) + strStart.length()));
                    writer.newLine();
                }
            }
            reader.close();
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void subtitlesForFolder(File folder){
        //File folder = new File(sourceFolderName);
        List<String> subFileNames = new ArrayList<String>();
        Arrays.asList(folder.listFiles()).parallelStream()
                .filter(file -> file.isFile() && file.getName().endsWith(fileNameSuffix))
                .forEach(file -> this.subtitlesForFile(file));
    }

    /**
     * Get English Words only and write into a new txt file in the same folder with the source
     * @param fileOrFolderName: abosolute file name
     */
    public void subtitles(String fileOrFolderName){
        File file = new File(fileOrFolderName);
        if(file.isDirectory()){
            this.subtitlesForFolder(file);
        }else{
            this.subtitlesForFile(file);
        }
        System.out.println("Completed!");
    }

    public static void main(String[] args) {
        EnglishSubtitles englishSubtitles = new EnglishSubtitles();
        System.out.print("輸入文件（夾）名 (Input File or Folder Name): ");
        Scanner scan = new Scanner(System.in);
        String fileOrFolderName =scan.nextLine();
        englishSubtitles.subtitles(fileOrFolderName);
    }
}
